package com.example.pharmacypick.service.impl;

import com.example.pharmacypick.dto.DrugDto;
import com.example.pharmacypick.dto.DrugUpdateDto;
import com.example.pharmacypick.mapper.DrugMapper;
import com.example.pharmacypick.mapper.DrugUpdateDtoMapper;
import com.example.pharmacypick.pojo.Drug;
import com.example.pharmacypick.service.DrugService;
import com.example.pharmacypick.utils.DateFormat;
import com.example.pharmacypick.vo.DataGridView;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DrugServiceImpl implements DrugService {

    @Autowired
    DrugMapper drugMapper;

//    更新库存要用到的mapper
    @Autowired
    DrugUpdateDtoMapper drugUpdateDtoMapper;

//    分页查询药品
    @Override
    public DataGridView findAllDrugs(DrugDto drugDto) {
//        分页
        try(Page<Object> pages = PageHelper.startPage(drugDto.getPageNum(), drugDto.getPageSize())){

            //在sql语句执行之前使用分页插件，保证查询顺利
            List<Drug> allDrugs = drugMapper.allDrugs(drugDto);

            //可以将drug转换为drugVo,再对drugVo对象集合封装在返回。

            return new DataGridView(pages.getTotal(),allDrugs);
        }
    }

//    添加药品
    @Override
    public void addDrug(DrugDto drugDto) {
        Drug drug=new Drug();
        BeanUtils.copyProperties(drugDto,drug);
        drugMapper.addDrug(drug);
    }

//    删除药品
    @Override
    public void deleteDrug(Long drugNum) {
        drugMapper.deleteDrug(drugNum);
    }

//    更新药品
    @Override
    public void updateDrug(DrugDto drugDto) {
        Drug drug=new Drug();
        BeanUtils.copyProperties(drugDto,drug);
        drugMapper.updateDrug(drug);
    }

    /**
     * 更新库存
     * @param prescriptionId 处方id号
     */
    @Override
    public void updateDrugStock(int prescriptionId) {
        //获取每个处方需要的药品,待更新的药品列表
        List<DrugUpdateDto> allDrugUpdateDtoList = drugUpdateDtoMapper.findAllDrugUpdateDtoByPrescriptionId(prescriptionId);
        //通过处方号来更新,根据查出的药品对象进行药品的库存更新
        drugUpdateDtoMapper.updateDrugStock(allDrugUpdateDtoList);
    }

}
